Completed
Push — master ( 88fa0f...de94f8 )
by greg
01:51
created

file.js ➔ getFolders   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
c 0
b 0
f 0
nc 1
dl 0
loc 13
rs 9.4285
nop 3
1
import path from 'path'
2
import mkdirp from 'mkdirp'
3
import fse from 'fs-extra'
4
import moment from 'moment'
5
6
import {
7
  abeExtend,
8
  coreUtils,
9
  cmsData,
10
  config
11
} from '../../'
12
13
export function getAllWithKeys(withKeys) {
14
  var files = cmsData.file.getFiles(path.join(config.root, config.data.url), true, 99, /\.json/)
15
  var filesArr = []
16
17
  files.forEach(function (file) {
18
    var cleanFile = file
19
    var json = cmsData.file.get(file.path)
20
21
    if(json.abe_meta.latest.date != null) {
22
      file.date = json.abe_meta.latest.date
23
      file.cleanDate = moment(json.abe_meta.latest.date).format('YYYY/MM/DD HH:MM:ss')
24
    }
25
26
    if(json.abe_meta != null) {
27
      var date = null
28
      if (json.abe_meta.latest.date !== null) {
29
        date = json.abe_meta.latest.date
30
      } else if (json.abe_meta.date !== null) {
31
        date = json.abe_meta.date
32
      }
33
      cleanFile.abe_meta = {
34
        date: date,
35
        type: (json.abe_meta.type != null) ? json.abe_meta.type : null,
36
        link: (json.abe_meta.link != null) ? json.abe_meta.link : null,
37
        template: (json.abe_meta.template != null) ? json.abe_meta.template : null,
38
        status: (json.abe_meta.status != null) ? json.abe_meta.status : null,
39
        cleanName: (json.abe_meta.cleanName != null) ? json.abe_meta.cleanName : null,
40
        cleanFilename: (json.abe_meta.cleanFilename != null) ? json.abe_meta.cleanFilename : null
41
      }
42
    }
43
    Array.prototype.forEach.call(withKeys, (key) => {
44
      var keyFirst = key.split('.')[0]
45
      cleanFile[keyFirst] = json[keyFirst]
46
    })
47
    filesArr.push(cleanFile)
48
  })
49
50
  var merged = cmsData.revision.getFilesMerged(filesArr)
51
52
  abeExtend.hooks.instance.trigger('afterGetAllFiles', merged)
53
  return merged
54
}
55
56
export function get(pathJson) {
57
  var json = {}
58
  pathJson = abeExtend.hooks.instance.trigger('beforeGetJson', pathJson)
59
  
60
  try {
61
    var stat = fse.statSync(pathJson)
62
    if (stat) {
63
      json = fse.readJsonSync(pathJson)
64
    }
65
  }catch(e) {
0 ignored issues
show
Coding Style Comprehensibility Best Practice introduced by
Empty catch clauses should be used with caution; consider adding a comment why this is needed.
Loading history...
66
  }
67
68
  json = abeExtend.hooks.instance.trigger('afterGetJson', json)
69
  return json
70
}
71
72
export function fromUrl(url) {
73
  var res = {
74
    root: '',
75
    draft: {
76
      dir: '',
77
      file: '',
78
      path: ''
79
    },
80
    publish: {
81
      dir: '',
82
      file: '',
83
      link: '',
84
      path: '',
85
      json: ''
86
    },
87
    json: {
88
      path: '',
89
      file: ''
90
    }
91
  }
92
93
  if(url != null) {
94
95
    var dir = path.dirname(url).replace(config.root, '')
96
    var filename = path.basename(url)
97
    var link = url.replace(config.root, '')
98
    link = link.replace(/^\//, '').split('/')
99
    link.shift()
100
    link = cmsData.fileAttr.delete('/' + link.join('/').replace(/\/$/, ''))
101
102
    let draft = config.draft.url
103
    let publish = config.publish.url
104
    let data = config.data.url
105
106
    res.root = config.root
107
108
    // set dir path draft/json
109
    res.draft.dir = coreUtils.file.changePath(dir, draft)
110
    res.json.dir = coreUtils.file.changePath(dir, data)
111
    res.publish.dir = coreUtils.file.changePath(dir, publish)
112
    res.publish.json = res.json.dir
113
114
    // set filename draft/json
115
    res.draft.file = filename
116
    res.publish.file = cmsData.fileAttr.delete(filename)
117
    res.publish.link = link
118
    res.json.file = filename.replace(`.${config.files.templates.extension}`, '.json')
119
    res.publish.json = path.join(res.json.dir, cmsData.fileAttr.delete(res.json.file))
120
121
    // set filename draft/json
122
    res.draft.path = path.join(res.draft.dir, res.draft.file)
123
    res.publish.path = path.join(res.publish.dir, res.publish.file)
124
    res.json.path = path.join(res.json.dir, res.json.file)
125
  }
126
  return res
127
}
128
129
export function getFiles(folder, flatten = false, level, extensions = /(.*?)/, inversePattern = false) {
130
131
  var arr = []
0 ignored issues
show
Unused Code introduced by
The assignment to variable arr seems to be never used. Consider removing it.
Loading history...
132
  arr = cmsData.file.read(
133
    folder.replace(/\/$/, ''),
134
    folder.replace(/\/$/, ''), 
135
    'files', 
136
    flatten, 
137
    extensions, 
138
    level, 
139
    0, 
140
    inversePattern
141
  )
142
143
  return arr
144
}
145
146
export function getFilesByType(pathFile, type = null) {
147
  try {
148
    var directory = fse.lstatSync(pathFile)
149
    if (!directory.isDirectory()) {
150
      mkdirp.sync(pathFile)
151
    }
152
  } catch (e) {
153
    mkdirp.sync(pathFile)
154
  }
155
  var files = cmsData.file.getFiles(pathFile, true, 20, new RegExp(`.${config.files.templates.extension}`))
156
157
  var result = []
158
159
  Array.prototype.forEach.call(files, (file) => {
160
    var val = cmsData.fileAttr.get(file.path).s
161
    if(type === null || val === type) result.push(file)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
162
  })
163
  return result
164
}
165
166
export function getFileObject(elt, pathLevel, base) {
167
  var cleanName = cmsData.fileAttr.delete(elt)
168
  var cleanNameNoExt = cleanName.replace(/\..+$/, '')
169
  var fileData = cmsData.fileAttr.get(elt)
170
171
  var date
172
  if (fileData.d) {
173
    date = fileData.d
174
  }else {
175
    var stat = fse.statSync(pathLevel)
176
    date = stat.mtime
177
  }
178
  var cleanFilePath = cmsData.fileAttr.delete(pathLevel).replace(config.root, '').replace(/^\/?.+?\//, '')
179
180
  var fileDate = moment(date)
181
  var duration = moment.duration(moment(fileDate).diff(new Date())).humanize(true)
182
183
  var filePath = pathLevel.replace(config.root, '')
184
  filePath = filePath.split('/')
185
  filePath.shift()
186
  filePath = filePath.join('/')
187
  var item = {
188
    'name': elt,
189
    'path': pathLevel,
190
    'cleanPathName': cmsData.fileAttr.delete(pathLevel),
191
    'cleanPath': pathLevel.replace(base + '/', ''),
192
    'date': date,
193
    'cleanDate': fileDate.format('YYYY/MM/DD HH:MM:ss'),
194
    'duration': duration,
195
    'cleanName': cleanName,
196
    'cleanNameNoExt': cleanNameNoExt,
197
    'cleanFilePath': cleanFilePath,
198
    'filePath': filePath,
199
    'type': 'file'
200
  }
201
202
  return item
203
}
204
205
export function read(base, dirName, type, flatten, extensions = /(.*?)/, max = 99, current = 0, inversePattern = false) {
206
  var arr = []
207
  var level = fse.readdirSync(dirName)
208
  var fileCurrentLevel = []
209
  let assets = config.files.templates.assets
210
211
  for (var i = 0; i < level.length; i++) {
212
    var pathLevel = dirName + '/' + level[i]
213
    var isFolder = true
214
    try {
215
      var directory = fse.lstatSync(pathLevel)
216
      if (!directory.isDirectory()) {
217
        isFolder = false
218
      }
219
    } catch (e) {
220
      isFolder = false
221
    }
222
    var match = (isFolder) ? true : (inversePattern) ? !extensions.test(level[i]) : extensions.test(level[i])
223
    if((type === 'files' || type === null) && match) {
224
225
      if(level[i].indexOf('.') > -1) {
226
        var item = cmsData.file.getFileObject(level[i], pathLevel, item)
0 ignored issues
show
Bug introduced by
The variable item seems to not be initialized for all possible execution paths. Are you sure getFileObject handles undefined variables?
Loading history...
227
        if(!flatten) item['folders'] = []
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
228
        arr.push(item)
229
        // push current file name into array to check if siblings folder are assets folder
230
        fileCurrentLevel.push(level[i].replace(/\..+$/, '') + assets)
231
      }
232
    }
233
    if(!fileCurrentLevel.indexOf(level[i]) >= 0 && match) {
234
      if(isFolder) {
235
        if(!flatten) {
236
          var index = arr.push(
237
            {
238
              'name': level[i],
239
              'path': pathLevel,
240
              'cleanPath': pathLevel.replace(base + '/', ''),
241
              'folders': [],
242
              'type': 'folder'
243
            }
244
          ) - 1
245
          if(current < max){
246
            arr[index].folders = cmsData.file.read(base, pathLevel, type, flatten, extensions, max, current + 1, inversePattern)
247
          }
248
        }else {
249
          if(type === 'folders' || type === null) {
250
            arr.push(
251
              {
252
                'name': level[i],
253
                'path': pathLevel,
254
                'cleanPath': pathLevel.replace(base + '/', ''),
255
                'type': 'folder'
256
              }
257
            )
258
          }
259
          if(current < max){
260
            Array.prototype.forEach.call(cmsData.file.read(base, pathLevel, type, flatten, extensions, max, current + 1, inversePattern), (files) => {
261
              arr.push(files)
262
            })
263
          }
264
        }
265
      }
266
    }
267
  }
268
269
  return arr
270
}